<?php defined('SYSPATH') OR die('No direct access allowed.');
 
class Bin_Controller extends Web_Controller {

	// Do not allow to run in production
 
	const ALLOW_PRODUCTION = FALSE;
	public $template = 'kohana/template';
  
	function index($input_error = false)
	{
		
		// In Kohana, all views are loaded and treated as objects.
		$this->template->content = new View('bin');
		$this->template->content->input_error = $input_error;
		$this->selected_page = 'bin';
		$this->template->title = 'Отложенные товары';
		$table = 'bz_items';
		
		$this->template->content->items_ses = $items = $this->session->get('items');
		
		$this->template->content->empty_bin = true;
		
		if(!empty($items)){
			
			if($_POST){
				
				foreach ($_REQUEST['items'] as $key => $counter){
					
					if(array_key_exists($key, $items)){
						$counter = intval($counter);
						
						if($counter > 0){
							$items[$key] = $counter;
						}else{
							unset($items[$key]);
						}
					}
					
				}
				
				$this->session->set('items', $items);
				$this->template->content->items_ses = $items = $this->session->get('items');
				
			}
			
			$this->template->content->empty_bin = false;
			
			$where = null;
			foreach ($items as $key => $count){
				$where .= $key.', ';
			}
			
			$this->template->content->items = $this->db->select($table.'.*, bz_types.tp_title, bz_firms.fr_title')->from($table)->
				join('bz_types', 'bz_types.tp_id', $table.'.tp_id', 'left')->
				join('bz_firms', 'bz_firms.fr_id', $table.'.fr_id', 'left')->
                                where('bz_items.it_archive = 0')->
					where('it_id in ('.substr($where, 0, -2).')')->orderby('it_model')->get(); 
				
		}else{
			
		}

	}
	
	function store(){
		
		$item_id = intval($this->uri->segment('itemid')); 
		$counter = intval($this->uri->segment('counter')); 
		
		if($item_id != 0 && $counter != 0){
			$items =  array($item_id => $counter); 
			$sess_items = $this->session->get('items');
			
			if(!empty($sess_items)){
				$items = $sess_items + $items;
			}
			 
			$this->session->set('items', $items);
		}
		 
		$sess_items = $this->session->get('items'); 
		echo(count($sess_items));
		exit();
		
	}

	function trash(){
		
		$item_id = $this->uri->segment('itemid'); 
		$items = $this->session->get('items');
		
		unset($items[$item_id]);
		$this->session->set('items', $items);

		exit(count($this->session->get('items')));
		
	}

	function printing()
	{
 
		// In Kohana, all views are loaded and treated as objects.
		$this->template->content = new View('print'); 
		
		if($_POST){
			
			$user_data['od_name'] = $_POST['request']['name'];
			$user_data['od_phone'] = $_POST['request']['phone'];
			$user_data['od_mail'] = $_POST['request']['mail'];
			$user_data['od_date'] = date('Y-m-d H:i:s');
			$user_data['od_total'] = 0; 
			$user_data['od_ip'] = $this->input->ip_address(); 
			 
			if((!valid::email($user_data['od_mail']) || !valid::phone($user_data['od_phone']) || !valid::alpha($user_data['od_name']) )){ 
				$_POST = false;
				$this->index(true);
				return ;;
			}
 
			cookie::set('name', $user_data['od_name']);
			cookie::set('mail', $user_data['od_mail']);
			cookie::set('phone', $user_data['od_phone']);
				 
			$this->template->content->items_ses = $items = $this->session->get('items');
		 		 
			$last_order = $this->db->select('*')->from('bz_order') 
				->where('od_name', $user_data['od_name'])
				->where('od_date > NOW() - INTERVAL 2 HOUR')
				->where('od_count', count($items))
				->where('od_phone', $user_data['od_phone'])->orderby('od_id', 'desc')->get(); 
		 	
  			if(isset($last_order[0])){
				$this->session->set('items', array());
				url::redirect('?orderid='.$last_order[0]->od_id);
				exit();
			}elseif(count($items) == 0){
				url::redirect();
				exit();
			}
			
			$this->template->content->data = $user_data;
			
			$res = $this->db->insert('bz_order', $user_data);
			if($res){
				
				$this->template->content->order_id = $this->db->select('*')->from('bz_order') 
					->limit('1')->orderby('od_id', 'desc')->get(); 
				$this->template->content->order_id = ($this->template->content->order_id[0]->od_id);							
 
				$this->template->content->title = 'Заявка №'.$this->template->content->order_id;
				$table = 'bz_items';
				
				$this->template->content->empty_bin = true;
				
				if(count($items) > 0){
					
					$this->template->content->empty_bin = false;
					
					$where = null;
					foreach ($items as $key => $count){
						$where .= $key.', ';
					}
					
					$this->template->content->items = $this->db->select($table.'.*, bz_groups.gr_title, bz_types.tp_title, bz_firms.fr_title')->from($table)->
						join('bz_types', 'bz_types.tp_id', $table.'.tp_id', 'left')->
						join('bz_firms', 'bz_firms.fr_id', $table.'.fr_id', 'left')->
						join('bz_groups', 'bz_groups.gr_id', $table.'.gr_id', 'left')->
							where('it_id in ('.substr($where, 0, -2).')')->orderby('it_model')->get(); 
					
					$total = $total_internet = 0;
					foreach ($this->template->content->items as $key ){
						
						$data = array();
						
						$data['od_id'] = $this->template->content->order_id;
						$data['gr_title'] =  $key->gr_title;
						$data['tp_title'] = $key->tp_title;
						$data['fr_title'] =  $key->fr_title;
						//$data['it_model'] =  $key->it_model;
						$data['oi_count'] = $items[$key->it_id];
                                                $data['it_id'] =  $key->it_id;

						//$data['it_internet_price'] = $key->it_internet_price;
						//$data['it_metric'] =  $key->it_metric;
						//$data['it_first_price'] = $key->it_first_price;
						
						$total += $data['oi_count'] * $key->it_first_price;
						$total_internet += $data['oi_count'] * formula($key);
						
						$this->db->insert('bz_order_items', $data);
						
					}					
					
					$data = array(
						'od_total' => $total_internet,
						'od_count' => count($items),
						'od_total_first' => $total
					);
					
					$this->db->update('bz_order', $data, 'od_id = '. $this->template->content->order_id);
					
					$this->session->set('items', array());
					
					unset($_POST);
					
					$this->template->content->start = date(DATE_FORMAT);
					$this->template->content->ender = date(DATE_FORMAT, mktime(0, 0, 0, date("m")  , date("d")+2, date("Y")));
					
				}else{
                                    url::redirect();
                                    exit();
				}
				
				$message =  $this->template->content->render();
				echo "$message";

                                $message = preg_replace("/<div(.*?)<\/div>/ms", '', $message);
 
                                $file_order_name = PATH_ORDER.$this->template->content->order_id.'_'.date('Y.m.d').'.html';
                                file_put_contents($file_order_name, $message);

                                $swift = email::connect();
                                
                                // From, subject and HTML message 
                                $from =  new Swift_Address(MAIL_MARKET, 'Магазин «C-NET Shopping»');
                                $subject =  '[C-NET Shopping] Интернет заявка #'.$this->template->content->order_id;
   
                                $message = new View('message');

                                $message->user_name = $user_data['od_name'];
                                $message->order_number = $this->template->content->order_id;
                                $message->exp_date = $this->template->content->ender;

                                $message_body = $message->render();
     
                                // Build recipient lists
                                $recipients = new Swift_RecipientList;

                                $recipients->addTo($user_data['od_mail'] , $user_data['od_name']);

                                $message = new Swift_Message($subject, null, "text/html");
 
                                // Attachment
                                $swiftfile = new Swift_File($file_order_name);
                                $attachment = new Swift_Message_Attachment($swiftfile, "Заявка_№".$this->template->content->order_id."_от_".date('d.m.Y'), "text/html");

                                $message->attach(new Swift_Message_Part($message_body));
                                $message->attach($attachment);

                                // Build the HTML message

                                if ($swift->send($message, $recipients, $from)){
                                  // Success
                                }else{
                                  // Failure
                                  echo 'К сожелению письмо отправить не удалось.';
                                }

                                // To Admins

                                $admin_message = new View('message_admin');

                                $admin_message->user_name = $user_data['od_name'];
                                $admin_message->order_number = $this->template->content->order_id;
                                $admin_message->exp_date = $this->template->content->ender;

                                $admin_message = $admin_message->render();

                                $recipients->addTo(MAIL_ADMIN, 'Ivan Chura');
                                //$recipients->addTo('root01@mail.ru', 'Шлавик Кошкин');
                                $recipients->addTo(MAIL_MARKET, 'Шлавик Кошкин');

                                $recipients->removeTo($user_data['od_mail']);

                                $message = new Swift_Message($subject, null, "text/html");

                                // Attachment

                                $message->attach(new Swift_Message_Part($admin_message));
                                $message->attach($attachment);

                                $from =  new Swift_Address(MAIL_ADMIN, 'Иван Чура');

                                $swift->send($message, $recipients, $from);
                                
                                // Disconnect
                                $swift->disconnect();

 
			}else{
				url::redirect();
			}
 	
		}else{
			url::redirect();
		}
		
		exit();
	}
	
	public function priselist()
	{

		download::force(FILE_PRISE, 'Price list is not available');
	}
} //
